package com.googlecode.groovy_toy_orm;

/**
 * @author: DavydovMD
 * Date: 11.04.13
 * Time: 12:23
 */
abstract public class TableMapper extends Mapper {
    String tableName


    public TableMapper(Mapper mapper, String table, String keyField = mapper.keyField) {
        super(mapper);
        this.tableName = table
        this.keyField = keyField
    }

    public TableMapper(MapperFields builder, String table, String keyField = builder.fields.first().name) {
        super(builder);
        this.tableName = table
        this.keyField = keyField
    }

    public String getPrefix(){
        tableName + "."
    }



    @Override
    public String getName(){
        "TableMapper $tableName (key:$keyField)"
    }

    /**
     * Get fully qualified field name (including table name)
     */
    @Override
    public String getFqSourceName(String field) {
        List from = getField(field).from
        if (from.size() != 1) return null
        return "${tableName}.${from.last()}"
    }


    @Override
    public Map<String, String> getFqSourceNames(String field) {
        Map ret = [:]
        builder.getField(field).from.each { String s ->
            ret.put(s, "${tableName}.${s}" as String)
        }
        ret
    }

}